import { Component, OnInit, OnDestroy, ViewChild, ElementRef, Compiler, ViewContainerRef, ComponentRef, Renderer, NgModule, EventEmitter } from "@angular/core";
import { Location } from "@angular/common";
import { DomSanitizer, BrowserModule, SafeResourceUrl } from "@angular/platform-browser";
import { Router, RouterState, ActivatedRoute, NavigationEnd } from "@angular/router";
import { Subject } from "rxjs/Subject";
import { ReplaySubject } from "rxjs/ReplaySubject";
import { Observable } from "rxjs/Observable";
import { Http } from "@angular/http";

import { CommentsService } from "../comments/comments.service";
import "rxjs/add/operator/switchMap";
import { UserService } from "user";

interface ColumnType {
  column_key: string;
  column_name: string;
  categories: [CategoryType];
}

interface CategoryType {
  category_key: string;
  category_name: string;
  granted: number;
}

interface ArticleType {
  is_grouping: number;
  category_key: string;
  group_id?: string;
  group_name?: string;
  summary?: string;
  poster?: string;
  group_articles: ArtcicleGroup[];
}

interface ArtcicleGroup {
  detail_id: string;
  column_name: string;
  category_key: string;
  category_name?: string;
  title: string;
  summary?: string;
  media_type: string;
  source_url: string;
  thumb_cdn_url: string;
  thumb_local_url?: string;
  access_level: string;
  add_time: string;
  file_size?: number;
}


@Component({
  selector: "method",
  templateUrl: "method.component.html",
  styleUrls: ["method.component.less"]
})
export class MethodComponent implements OnInit {
  XZFCategories: CategoryType[];
  articles: ArticleType[];
  selectedCategory: CategoryType;
  articlesGroupOfSelectedCategory: ArticleType[];

  caseArticleList: ArtcicleGroup[] = []; //案例复盘列表
  hotVoideList: ArtcicleGroup[];  //热门课程


  modalFlag: string;
  videoUrl: string;  // 视频地址

  category: string;
  startTime: string = "";
  limit: number = 10;
  tabNo: string = "xuezhanfa";

  caseStartTime: string = "";

  timeoutId = <any>(1);
  timeoutCase = <any>(1);
  @ViewChild("loadTracker") loadTracker: ElementRef;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private commentsService: CommentsService,
    private userService: UserService,
    private http: Http,
    private renderer: Renderer,
    private compiler: Compiler,
    private sanitizer: DomSanitizer,
    private location: Location
  ) {}


  ngOnInit() {
    this.userService.loginStatusSub.subscribe((status) => {
      if (status) {
        this.getXZFArticles();
        this.getHotVoide();
      }
    });
    this.userService.tokenSub.subscribe((str) => {
      if (str === "Token") {
        this.getXZFArticles();
        this.getHotVoide();
      }
    });
  }

  private getXZFArticles() {
    this.commentsService.getXZFArticles().subscribe(data => {
      if (data.code === 0 && data.msg === "success") {
        this.XZFCategories = this.filteCategories(this.getCategories(data.data.columns, "xuezhanfa"), "gegugenzong");
        this.articles = data.data.articles;
        this.onClickCategory(this.XZFCategories[0]);
        this.getCaseArticleList();
      } else if(data.code === 1002 && data.msg === "Expired token") {
        this.userService.updateLogStatus(false);
        this.userService.setModal("login");
      }
    });
  }

  private getCategories(columns: ColumnType[], columenName: string) {
    for ( let i = 0 ; i < columns.length ; i ++ ) {
      if (columns[i].column_key === columenName) {
        return columns[i].categories;
      }
    }
  }

  private filteCategories(categories: CategoryType[], category_name: string) {
    for (let j = 0 ; j < categories.length ; j ++ ) {
      if (categories[j].category_key === category_name) {
        categories.splice(j , 1);
      }
    }
    return categories;
  }

  onClickCategory(category: CategoryType) {
    this.startTime = "";
    this.selectedCategory = category;
    this.articlesGroupOfSelectedCategory = [];
    this.articlesGroupOfSelectedCategory = this.getArticlesOfSelectedCategory(category.category_key);
    if (this.articlesGroupOfSelectedCategory.length > 0 && this.articlesGroupOfSelectedCategory[0].is_grouping === 0) {
      this.getArticleList();
    }
  }

  private getArticlesOfSelectedCategory(category_key: string) {
    let articles: ArticleType[] = [];
    for (let i = 0 ; i < this.articles.length ; i ++ ) {
      if (this.articles[i].category_key === category_key) {
        articles = articles.concat(JSON.parse(JSON.stringify(this.articles[i])));
      }
    }
    /* 后台调整为顺排，原则上不要在客户端自定义排序，以免后端失去控制
    for (let j = 0 ; j < articles.length ; j ++ ) {
      articles[j].group_articles.reverse();
    }
    */
    if (articles.length > 0 && articles[0].is_grouping === 0 ) {
      this.startTime = articles[0].group_articles[articles[0].group_articles.length - 1].add_time;
    }
    return articles;
  }

  private getHotVoide() {
    this.commentsService.getHotVoide().subscribe(data => {
      if (data.length > 0) {
        this.hotVoideList = data;
      }
    });
  }


  private getArticleList() {
    this.category = this.selectedCategory.category_key;
    this.commentsService.getArticleList(this.startTime, this.limit, this.category, this.tabNo).subscribe(data => {
      if ( data.code === 0 && data.msg === "success" && data.data.length > 0) {
        this.articlesGroupOfSelectedCategory[0].group_articles = this.articlesGroupOfSelectedCategory[0].group_articles.concat(data.data[0].group_articles);
        this.startTime = this.articlesGroupOfSelectedCategory[0].group_articles[this.articlesGroupOfSelectedCategory[0].group_articles.length - 1].add_time;
      } else if(data.code === 1002 && data.msg === "Expired token") {
        this.userService.updateLogStatus(false);
        this.userService.setModal("login");
      } else {
        console.info("get ArticleList err: ", data.errors);
      }
    });
  }

  private getCaseArticleList() {
    this.commentsService.getArticleList("", 4, "gegugenzong", this.tabNo).subscribe(data => {
      if ( data.code === 0 && data.msg === "success" && data.data.length > 0 ) {
        this.caseArticleList = this.caseArticleList.concat(data.data[0].group_articles);
        this.caseStartTime = this.caseArticleList[this.caseArticleList.length - 1].add_time;
      } else if(data.code === 1002 && data.msg === "Expired token") {
        this.userService.updateLogStatus(false);
        this.userService.setModal("login");
      } else {
        console.log("get CaseArticleList err:", data.errors);
      }
    });
  }

  loadMore(e: WheelEvent) {
    if (this.articlesGroupOfSelectedCategory.length > 0 && this.articlesGroupOfSelectedCategory[0].is_grouping === 0 && this.isLoadMoreActive()) {
      clearTimeout(this.timeoutId);
      this.timeoutId = setTimeout(() => {
        this.getArticleList();
      }, 200);
    }
  }

  switchModal(action: string, url?: string) {
    if ( action === "active" && url && url !== "") {
      this.modalFlag = "active";
      this.videoUrl = url;
    }
    else {
      this.modalFlag = "";
    }
  }

  private isLoadMoreActive() {
    if (!this.loadTracker) return false;
    let loadTrackerElem: HTMLElement = this.loadTracker.nativeElement;
    let parentElem = loadTrackerElem.parentElement;
    let top = loadTrackerElem.getBoundingClientRect().top;
    let parentRect = parentElem.getBoundingClientRect();
    // console.debug('is load more active: ', parentRect.top, '<=', top, '<=', parentRect.bottom);
    return (top >= parentRect.top && top <= parentRect.bottom + 10);
  }
}